﻿using YNTK.Common.Core.Manager;
using YNTK.Common.Enum;
using YNTK.Common.Extension;
using YNTK.Common.Filter;
using YNTK.Dependency;
using YNTK.DynamicApiController;
using YNTK.FriendlyException;
using YNTK.SubDev.Interfaces.ZyOaGoods;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YNTK.SubDev.Entitys;
using YNTK.SubDev.Entitys.Dto.ZyOaGoods;
using Yitter.IdGenerator;
using YNTK.Common.Helper;
using YNTK.JsonSerialization;

namespace YNTK.SubDev.ZyOaGoods
{
    /// <summary>
    /// 仓库管理服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "SubDev",Name = "ZyOaGoods", Order = 200)]
    [Route("api/SubDev/[controller]")]
    public class ZyOaGoodsService : IZyOaGoodsService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<ZyOaGoodsEntity> _zyOaGoodsRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="ZyOaGoodsService"/>类型的新实例
        /// </summary>
        public ZyOaGoodsService(
            ISqlSugarRepository<ZyOaGoodsEntity> zyOaGoodsRepository,
            IUserManager userManager)
        {
            _zyOaGoodsRepository = zyOaGoodsRepository;            
            _db = _zyOaGoodsRepository.Context;
            _userManager = userManager;
        }

        /// <summary>
        /// 获取仓库管理
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<ZyOaGoodsEntity>().FirstAsync(p => p.Id == id);
            var output = entity.Adapt<ZyOaGoodsInfoOutput>();
            return output;
        }

        /// <summary>
		/// 获取仓库管理列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] ZyOaGoodsListQueryInput input)
        {
            var sidx = input.sidx == null ? "creatorTime" : input.sidx;
            var areaList = input.area != null ? input.area.Split(',').ToList().ToJson() :null;
            var data = await _db.Queryable<ZyOaGoodsEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.name), p => p.Name.Contains(input.name))
                .WhereIF(!string.IsNullOrEmpty(input.area), p => p.Area.Equals(areaList))
                .Select(it=> new 
                {
                    id = it.Id,
                    name=it.Name,
                    desPerson=it.DesPerson,
                    desPersonPhone=it.DesPersonPhone,
                    admin=it.Admin,
                    area=it.Area,
                    address=it.Address,
                    creatorTime=it.CreatorTime,
                    creatorUserId=it.CreatorUserId,
                }).MergeTable().Select<ZyOaGoodsListOutput>().OrderBy(sidx+" "+input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return TkPageResult<ZyOaGoodsListOutput>.SqlSugarPageResult(data);
        }

        /// <summary>
        /// 新建仓库管理
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] ZyOaGoodsCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var entity = input.Adapt<ZyOaGoodsEntity>();
            entity.Id = YitIdHelper.NextId().ToString();
            entity.CreatorTime = DateTime.Now;  
            entity.CreatorUserId = _userManager.UserId;
            var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1000);
        }

        /// <summary>
        /// 更新仓库管理
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] ZyOaGoodsUpInput input)
        {
            var entity = input.Adapt<ZyOaGoodsEntity>();
            entity.LastModifyer = _userManager.UserId;
            entity.LastModifyTime = DateTime.Now;  
            var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1001);
        }

        /// <summary>
        /// 删除仓库管理
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var entity = await _db.Queryable<ZyOaGoodsEntity>().FirstAsync(p => p.Id == id);
            _ = entity ?? throw YNTKException.Oh(ErrorCode.COM1005);
            var isOk = await _db.Deleteable<ZyOaGoodsEntity>().Where(d => d.Id == id).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1002);
        }
    }
}
